package com.badibadi.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.badibadi.infos.MyFriendsModel;
import com.badibadi.infos.Results;
import com.badibadi.infos.TempIMGAddressModel;
import com.badibadi.logic.ImgFileListActivity;
import com.badibadi.mail.Mail15_huifuActivity;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.ImageTools;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.SinaExpressionTools;
import com.badibadi.mytools.Utils;
import com.badibadi.mytools.XUtils;
import com.badibadi.uniclubber.R;
import com.badibadi.uniclubber.SinaExpressionActivity;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.view.my_view.MyGridView;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

//startActivity
public class Club_SendDynamicActivity extends SendDynamicActivity {// activity_send_dynamic_return_btn
	private String TAG = "Club_SendDynamicActivity";
	private List<String> pathStrings;
	private Results results;
	private String uid, cid, head;
	private List<TempIMGAddressModel> addressModels_main, addressModels;
	private GridView up_picture_GridView;
	private Item_Adapter_2 adapter;
	private DisplayImageOptions options;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				try {
					Utils.ExitPrgress(Club_SendDynamicActivity.this);
					Utils.showMessage(Club_SendDynamicActivity.this,
							getResources().getString(R.string.l_net_error));
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 2:
				try {
					Utils.ExitPrgress(Club_SendDynamicActivity.this);
					Utils.showMessage(Club_SendDynamicActivity.this,
							getResources().getString(R.string.fasongchenggong));
					if (results.isRet()) {
						resh();
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 3:
				try {
					Utils.ExitPrgress(Club_SendDynamicActivity.this);
					Utils.showMessage(Club_SendDynamicActivity.this,
							getResources().getString(R.string.l_xb44));
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 2000:
				try {
					Utils.ExitProgress_hen(Club_SendDynamicActivity.this);
					// Utils.ExitPrgress_Noclose(Club_SendDynamicActivity.this);
					Utils.showMessage(Club_SendDynamicActivity.this,
							getResources().getString(R.string.l_xb18));
					String result = msg.getData().getString("path");
					pathStrings.add(result);
					addressModels_main.addAll(qiege_content(result, ","));
					adapter.notifyDataSetChanged();
//					   
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		flags = 1;

	}

	public void resh() {
		Intent intent = new Intent(Club_SendDynamicActivity.this,
				ClubHomepageActivity.class);
		intent.putExtra("cid", cid);
		Club_SendDynamicActivity.this.startActivity(intent);
		Club_SendDynamicActivity.this.finish();
	}

	/**
	 * 切割数据
	 * 
	 * @param con
	 * @param pand
	 * @return
	 */
	private List<TempIMGAddressModel> qiege_content(String con, String pand) {
		String[] ccc = con.split(pand);
		List<TempIMGAddressModel> addressModels = new ArrayList<TempIMGAddressModel>();
		if (ccc.length > 1) {
			for (int i = 0; i < ccc.length; i++) {
				TempIMGAddressModel addressModel = new TempIMGAddressModel();
				addressModel.setImg_address(ccc[i]);
				addressModels.add(addressModel);
			}
		} else {
			TempIMGAddressModel addressModel = new TempIMGAddressModel();
			addressModel.setImg_address(con);
			addressModels.add(addressModel);
		}
		return addressModels;
	}

	@Override
	public void init() {
		// TODO Auto-generated method stub
		super.init();
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.ic_stub)
				.showImageForEmptyUri(R.drawable.noimage)
				.showImageOnFail(R.drawable.noimage).cacheInMemory()
				.cacheOnDisc().displayer(new RoundedBitmapDisplayer(5)).build();
		try {
			// uid = getIntent().getStringExtra("uid");
			cid = getIntent().getStringExtra("cid");
			head = getIntent().getStringExtra("head");
		} catch (Exception e) {
			// TODO: handle exception
		}
		uid = Utils.getUid(Club_SendDynamicActivity.this);

		pathStrings = new ArrayList<String>();
		addressModels_main = new ArrayList<TempIMGAddressModel>();
		up_picture_GridView = (GridView) findViewById(R.id.up_picture_GridView);
		adapter = new Item_Adapter_2(Club_SendDynamicActivity.this);
		up_picture_GridView.setAdapter(adapter);
		this.findViewById(R.id.biaoqing).setOnClickListener(this);
		try {
			// // 头像
			ImageLoader.getInstance().displayImage(
					Constants.BadiDownImgUrl + "/"
							+ Utils.getu_Head(Club_SendDynamicActivity.this)
							+ Constants.appPhoto4img, head2, options);
		} catch (Exception e) {
			// TODO: handle exception
		}
		this.findViewById(R.id.activity_send_dynamic_send).setOnClickListener(
				this);
		this.findViewById(R.id.activity_send_dynamic_lock).setOnClickListener(
				this);

		TextView activity_send_dynamic_name = (TextView) this
				.findViewById(R.id.activity_send_dynamic_name);
		activity_send_dynamic_name.setText(""
				+ Utils.getu_Name(Club_SendDynamicActivity.this));
		// ImageView
		// senddynamic_head=(ImageView)this.findViewById(R.id.senddynamic_head);
		this.findViewById(R.id.activity_send_dynamic_return_btn)
				.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						resh();
					}
				});
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.activity_send_dynamic_lock:
			setPopWindowsVisible();
			break;
		case R.id.activity_send_dynamic_send:
			send();
			break;
		case R.id.create_new_poly_layout01:
			setJurisdictionOnClickListener(0);
			break;
		case R.id.create_new_poly_layout02:
			setJurisdictionOnClickListener(1);
			break;
		case R.id.activity_send_dynamic_at_friends:
			Intent intent = new Intent(Club_SendDynamicActivity.this,
					MyFriendsResultActivity.class);
			startActivityForResult(intent, 3);
			break;
		case R.id.biaoqing:
			Intent intent2 = new Intent(Club_SendDynamicActivity.this,
					SinaExpressionActivity.class);
			startActivityForResult(intent2, ACTIVITY_BIAOQING);
			break;
		default:
			break;
		}
	}

	protected void send() {
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				Map<String, Object> map = new HashMap<String, Object>();
				try {
					map.put("trends", fengzhuang());
					System.out.println("map"+map);
					System.out.println(fengzhuang());
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					   
				}
				//    ("俱乐部发送动态传送的数据是:" + map.toString());
//				   
				String content = Utils.sendRequest(map, Constants.BadiUrl_1
						+ "club/trends");
				System.out.println("julebu"+content);
				if (content != null) {
					results = Utils.checkResult_NNN(
							Club_SendDynamicActivity.this, content);
//					   
//							"俱乐部动态接收到的数据是：" + content + " "
//									+ results.getRetmsg());
					if (results != null && !results.getRetmsg().equals("null")) {
						try {
							handler.sendEmptyMessage(2);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							   
						}
					} else {
						handler.sendEmptyMessage(3);
					}
				} else {
					handler.sendEmptyMessage(1);
				}
			}
		});
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == 4) {
			resh();
		}
		return super.onKeyDown(keyCode, event);
	}

	private JSONObject fengzhuang() throws JSONException {

		if (jurisdiction == 1) {
			p_status = 0;
		} else if (jurisdiction == 0) {
			p_status = 1;
		}
		final String contents = SinaExpressionTools
				.replaceAllReplaceToPath(et_sendDynamic.getText().toString()
						.trim());
		//    
		String trends_img = "";

		JSONObject object1 = new JSONObject();
		object1.put("uid", uid);
		object1.put("contents", contents);
		object1.put("map_x", Latitude);
		object1.put("map_y", Longitude);
		object1.put("address", address);
		if(addressModels_main!=null && !addressModels_main.isEmpty())
		{
			StringBuffer buffer=new StringBuffer("");
			for(int i=0;i<addressModels_main.size();i++)
			{
				buffer.append(addressModels_main.get(i).getImg_address()+",");
			}
			String bb=buffer.toString();
			object1.put("trends_img",bb.substring(0, bb.length() - 1));
		}else
		{
			object1.put("trends_img", "");
		}
//		if (pathStrings != null && !pathStrings.isEmpty()) {
//			for (int i = 0; i < pathStrings.size(); i++) {
//				trends_img += pathStrings.get(i) + ",";
//				   
//			}
//		} else {
//			trends_img = "";
//		}
//		if (!trends_img.equals("")) {
//			object1.put("trends_img",
//					trends_img.substring(0, trends_img.length() - 1));
//		} else {
//			object1.put("trends_img", "");
//		}
		object1.put("cid", cid);
		object1.put("club_status", "" + p_status);
		
		return object1;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		/**
		 * at好友
		 */
		if (requestCode == 3 && resultCode == 3) {
			// et_sendDynamic.setText(et_sendDynamic.getText().toString()+data.getStringExtra("result"));
			List<MyFriendsModel> listObj = (ArrayList<MyFriendsModel>) data
					.getSerializableExtra("result");

			for (int i = 0; i < listObj.size(); i++) {
				if (listObj.get(i).isJudge() == true)
					et_sendDynamic.setText(""
							+ et_sendDynamic.getText().toString() + "@"
							+ listObj.get(i).getNickName() + " ");
			}
//			   ("我是回传数据" + listObj.get(0).getNickName());
		}

		// 点击表情后回调
		if (requestCode == ACTIVITY_BIAOQING
				&& resultCode == SinaExpressionActivity.ACTIVITY_BIAOQING
				&& flags == 1) {

			if (data != null) {
				String con = data.getExtras().getString("result");
				String con1 = et_sendDynamic.getText().toString();
				String con2 = con1 + con;

				if (con2.length() > limit) {
					Utils.showMessage(this,
							getResources().getString(R.string.l_xb45) + limit);
				} else {
					String content2 = data.getStringExtra("result");
					int index = et_sendDynamic.getSelectionStart();
					Editable edit = et_sendDynamic.getEditableText();
					edit.insert(index, content2);

					// et_sendDynamic.setText(con2);
					// et_sendDynamic.setSelection(con2.length());
				}

				// new HtmlUtils(SendDynamicActivity.this,
				// et_sendDynamic,et_sendDynamic.getText().toString()).showEditText();
			}
		}

//		   ("传出" + requestCode + " " + "回传" + resultCode);
		if (requestCode == 5 && resultCode == 5 && flags == 1) {
			ArrayList<String> filelist = data.getStringArrayListExtra("files");
			// addressModels = new ArrayList<TempIMGAddressModel>();
			// if (filelist != null && !filelist.isEmpty()) {
			// for (int i = 0; i < filelist.size(); i++) {
			// TempIMGAddressModel model = new TempIMGAddressModel();
			// model.setImg_address(filelist.get(i));
			// addressModels.add(model);
			// }
			// }
			// addressModels_main.addAll(addressModels);
			// adapter.notifyDataSetChanged();
			// Utils.showPrgress(SendDynamicActivity.this);
			// Utils.showMessage(Club_SendDynamicActivity.this, getResources()
			// .getString(R.string.l_xb46));
			XUtils.UpImg_ceshi_douhaoXUtils(filelist,
					Club_SendDynamicActivity.this, handler);
			// for (int i = 0; i < filelist.size(); i++) {
			//    ("获取到的图片地址是:" + filelist.get(i));
			// }
		}

	}

	@Override
	public void setPopWindowsVisible() {
		// TODO Auto-generated method stub
		super.setPopWindowsVisible();
		ll_2.setVisibility(View.GONE);
		i_2.setVisibility(View.GONE);
		pop_quanxian_setting_huiyuan.setText(getResources().getString(
				R.string.l_xb30));
		pop_quanxian_setting_allperson.setText(getResources().getString(
				R.string.AllThePeople));
	}

	private class Item_Adapter_2 extends BaseAdapter {
		private Context context;

		public Item_Adapter_2(Context context) {
			this.context = context;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return addressModels_main.size() + 1;
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return addressModels_main.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(final int arg0, View convertView, ViewGroup arg2) {
			if (arg0 < addressModels_main.size()) {
				// if (convertView == null) {
				// convertView = ViewHolder.buildView(context,
				// R.layout.sure_upimg_item_main, arg2);
				// }
				// ViewHolder viewHolder = (ViewHolder) convertView.getTag();
				LayoutInflater viewHolder = LayoutInflater.from(context);
				convertView = viewHolder.inflate(R.layout.sure_upimg_item_main,
						null);
				ImageView sure_upimg_item_img = (ImageView) convertView
						.findViewById(R.id.sure_upimg_item_img);
				// pathtobitmap(addressModels_main.get(arg0).getImg_address(),
				// sure_upimg_item_img);
				ImageLoader.getInstance().displayImage(
						Constants.BadiDownImgUrl
								+ addressModels_main.get(arg0).getImg_address()
								+ Constants.App9block, sure_upimg_item_img,
						options);
				sure_upimg_item_img
						.setOnLongClickListener(new OnLongClickListener() {
							@Override
							public boolean onLongClick(View arg10) {
								new AlertDialog.Builder(context)
										.setTitle(
												getResources().getString(
														R.string.l_xb47))
										.setIcon(R.drawable.icon)
										.setMessage(
												getResources().getString(
														R.string.l_xb48))
										.setPositiveButton(
												getResources().getString(
														R.string.Yes),
												new DialogInterface.OnClickListener() {

													@Override
													public void onClick(
															DialogInterface arg20,
															int arg1) {
														// addressModels_main.get(arg0).getImg_address();
														addressModels_main
																.remove(arg0);
														Notific();
													}
												})
										.setNegativeButton(
												getResources().getString(
														R.string.No),
												new DialogInterface.OnClickListener() {

													@Override
													public void onClick(
															DialogInterface arg0,
															int arg1) {

													}
												}).show();
								return false;
							}
						});
			}

			if (addressModels_main.isEmpty()
					|| arg0 >= addressModels_main.size()) {
				//    ("运行2：" + arg0 + " " +
				// imgAddressModels.size());
				// if (convertView == null) {
				// convertView = ViewHolder.buildView(context,
				// R.layout.sure_upimg_main, arg2);
				// }
				// ViewHolder viewHolder = (ViewHolder) convertView.getTag();
				LayoutInflater viewHolder = LayoutInflater.from(context);
				convertView = viewHolder
						.inflate(R.layout.sure_upimg_main, null);
				ImageView sure_upimg_item_img_add = (ImageView) convertView
						.findViewById(R.id.sure_upimg_item_img_add);
				sure_upimg_item_img_add
						.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View arg0) {
								// TODO Auto-generated method stub
								Intent intent = new Intent(
										Club_SendDynamicActivity.this,
										ImgFileListActivity.class);
								intent.putExtra("panduan", "no_set");
								// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
								startActivityForResult(intent, 5);
								// context.startActivity(intent);
							}
						});
			}
			return convertView;
		}

		private void pathtobitmap(String p, ImageView im) {
			im.setImageBitmap(com.badibadi.mytools.ImageLoader
					.decodeSampledBitmapFromResource(p, 60));
		}

		public void Notific() {
			Item_Adapter_2.this.notifyDataSetChanged();
		}
	}
}
